package com.rybbaby.tss.api.classes;

import com.rybbaby.tss.core.annotation.Token;
import com.rybbaby.tss.core.bean.PageBean;
import com.rybbaby.tss.core.hqlsearch.HqlGenerateUtil;
import com.rybbaby.tss.core.utils.AppResponse;
import com.rybbaby.tss.core.utils.DateUtil;
import com.rybbaby.tss.core.utils.StringUtils;
import com.rybbaby.tss.core.web.controller.BaseController;
import com.rybbaby.tss.front.tssClasses.entity.TssClasses;
import com.rybbaby.tss.front.tssClasses.service.ITssClassesService;
import com.rybbaby.tss.front.tssMemberPackage.service.ITssMemberPackageService;
import com.rybbaby.tss.front.tssPertainRelation.entity.TssPertainRelation;
import com.rybbaby.tss.front.tssPertainRelation.service.ITssPertainRelationService;
import com.rybbaby.tss.front.tssStudent.entity.TssStudent;
import com.rybbaby.tss.front.tssStudent.service.ITssStudentService;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 谢进伟
 * @description 班级相关API
 * @createDate 2018/1/22 10:36
 */
@CrossOrigin
@RestController
@RequestMapping(value = "api/classes", produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public class ClassApi extends BaseController {

    @Autowired
    private ITssClassesService classesService;
    @Autowired
    private ITssStudentService studentService;
    @Autowired
    private ITssPertainRelationService pertainRelationService;
    @Autowired
    private ITssMemberPackageService memberPackageService;

    /**
     * 接口默认返回
     *
     * @return
     */
    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index() {
        return new AppResponse("hello ,welcome to R.Y.B common service API", 200).jsonResponse(false);
    }

    /**
     * 获取班级列表
     *
     * @param condition 检索条件对象
     * @return
     */
    @Token(validateSign = true)
    @RequestMapping(value = "classList", method = RequestMethod.GET)
    public String classList(TssClasses condition, @RequestParam(required = false, defaultValue = "1") Integer pageNo, @RequestParam(required = false, defaultValue = "20") Integer pageSize) {
        AppResponse apiResponse = new AppResponse();
        try {
            DetachedCriteria dc = DetachedCriteria.forClass(TssClasses.class);
            HqlGenerateUtil.fillDetachedCriteria(dc, condition, getParameterMap(getRequest()));
            dc.addOrder(Order.desc("startTime"));
            PageBean pageBean = this.classesService.pageList(dc, pageNo, pageSize);
            List<?> list = pageBean.getList();
            List<Map<String, Object>> data = new ArrayList<>(list.size());
            for (Object o : list) {
                TssClasses tssClasses = (TssClasses) o;
                Map<String, Object> map = new HashMap<>();
                String classesId = tssClasses.getId();
                int studentCount = this.classesService.getStudentCount(classesId);
                map.put("id", classesId);//班级id
                map.put("name", tssClasses.getName());//班级名称
                map.put("studentCount", studentCount);//学生人数
                data.add(map);
            }
            apiResponse.setData(data);
        } catch (Exception e) {
            e.printStackTrace();
            apiResponse.setResCode(500);
            String message = e.getMessage();
            apiResponse.setResMsg("服务器端异常" + (StringUtils.isNotBlank(message) ? ("(" + message + ")") : "") + "!");
        }
        return apiResponse.jsonResponse(true);
    }

    /**
     * 获取班级下面的学生列表
     *
     * @param classesId 班级id
     * @return
     */
    @Token(validateSign = true)
    @RequestMapping(value = "getStudentsByClassId", method = RequestMethod.GET)
    public String getStudentsByClassId(String classesId) {
        AppResponse apiResponse = new AppResponse();
        try {
            List<TssStudent> students = this.studentService.getStudentsByClassId(classesId);
            List<Map<String, Object>> data = new ArrayList<>(students.size());
            for (TssStudent student : students) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", student.getId());//学生id
                map.put("headPortrait", student.getHeadPortrait());//头像
                map.put("name", student.getName());//名字
                map.put("nickName", student.getNickName());//昵称
                map.put("quickMark", student.getQuickMark());//二维码
                map.put("contactPhone", student.getContactPhone());//联系电话
                map.put("telePhone", student.getTelePhone());//固定电话
                data.add(map);
            }
            apiResponse.setData(data);
        } catch (Exception e) {
            e.printStackTrace();
            apiResponse.setResCode(500);
            String message = e.getMessage();
            apiResponse.setResMsg("服务器端异常" + (StringUtils.isNotBlank(message) ? ("(" + message + ")") : "") + "!");
        }
        return apiResponse.jsonResponse(true);
    }

    /**
     * 获取班级下面的学生详细信息
     *
     * @param studentId 学生id
     * @return
     */
    @Token(validateSign = true)
    @RequestMapping(value = "getStudentsDetail", method = RequestMethod.GET)
    public String getStudentsDetail(String studentId) {
        AppResponse apiResponse = new AppResponse();
        try {
            TssStudent student = this.studentService.get(studentId);
            if (student != null) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", student.getId());//学生id
                map.put("headPortrait", student.getHeadPortrait());//头像
                map.put("name", student.getName());//名字
                map.put("nickName", student.getNickName());//昵称
                map.put("quickMark", student.getQuickMark());//二维码
                map.put("sex", student.getSex());//性别
                map.put("birthdayDate", DateUtil.format(student.getBirthdayDate(), "yyyy-MM-dd"));//生日
                map.put("sex", student.getSex());//性别
                map.put("contactPhone", student.getContactPhone());//联系电话
                //班级
                List<String> classNames = new ArrayList<>();
                List<TssClasses> studentClasses = this.classesService.getStudentClasses(studentId);
                if (studentClasses != null && !studentClasses.isEmpty()) {
                    for (TssClasses studentClass : studentClasses) {
                        classNames.add(studentClass.getName());
                    }
                }
                map.put("classes", classNames);
                //家人
                List<TssPertainRelation> pertainRelations = pertainRelationService.findByProperty("studentId", studentId);
                map.put("pertainRelations", pertainRelations);
                //课时包
                List<Map<String, Object>> packs = new ArrayList<>();
                List<Map<String, Object>> packages = this.memberPackageService.getListByMemberId(studentId, null);
                if (packages != null && !packages.isEmpty()) {
                    for (Map<String, Object> aPackage : packages) {
                        Map<String, Object> pk = new HashMap<>();
                        pk.put("packageId", aPackage.get("packageId"));//课时包id
                        pk.put("name", aPackage.get("name"));//课时包名称
                        pk.put("memberPackageId", aPackage.get("id"));//会员课时包id
                        pk.put("totalClassHour", aPackage.get("totalClassHour"));//总课时
                        pk.put("packageStatus", aPackage.get("packageStatus"));//状态(1、 使用中 2、 待激活 3、 注销)
                        pk.put("presentClassHour", aPackage.get("presentClassHour"));//赠送课时数
                        pk.put("unusedClassHour", aPackage.get("unusedClassHour"));//未消耗课时数
                        pk.put("usableTotalClassHour", aPackage.get("usableTotalClassHour")); //可用课时数
                        pk.put("surplusClassHour", aPackage.get("surplusClassHour")); //剩余课时数
                        pk.put("surplusFormalClassHour", aPackage.get("surplusFormalClassHour")); //剩余正课时
                        pk.put("surplusPresentClassHour", aPackage.get("surplusPresentClassHour")); //剩余赠课时
                        pk.put("selectedClassHour", aPackage.get("selectedClassHour")); //已选班课时数
                        pk.put("consumptionClassHour", aPackage.get("consumptionClassHour")); //已消耗课时数
                        pk.put("positiveConsumptionClassHour", aPackage.get("positiveConsumptionClassHour")); //已消耗课时数(正)
                        pk.put("giftConsumptionClassHour", aPackage.get("giftConsumptionClassHour")); //已消耗课时数(赠)
                        pk.put("positiveUnusedClassHour", aPackage.get("positiveUnusedClassHour")); //未消耗课时数(正)
                        pk.put("giftUnusedClassHour", aPackage.get("giftUnusedClassHour")); //未消耗课时数(赠)
                        pk.put("remediationClassHour", aPackage.get("remediationClassHour")); //补课可用课时数
                        packs.add(pk);
                    }
                }
                map.put("packages", packs);
                apiResponse.setData(map);
            } else {
                apiResponse.setResCode(-1);
                apiResponse.setResMsg("学生信息不存在!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            apiResponse.setResCode(500);
            String message = e.getMessage();
            apiResponse.setResMsg("服务器端异常" + (StringUtils.isNotBlank(message) ? ("(" + message + ")") : "") + "!");
        }
        return apiResponse.jsonResponse(true);
    }
}
